﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class DrawLineManager : MonoBehaviour {

	[SerializeField]private GameObject line;
	[SerializeField]private GameObject egg;
	[SerializeField]private List<Vector3> wayPoints = new List<Vector3>();

	void Update()
	{
		if (Input.GetMouseButtonDown(0))  
		{  
			ClearLine();
			//添加起点
			wayPoints.Add (Input.mousePosition);
		}  
		if (Input.GetMouseButtonUp(0))  
		{  //添加终点
			wayPoints.Add (Input.mousePosition); 
			DrawLine ();
		} 
	}

	void DrawLine()
	{
		if(wayPoints.Count > 1)
		{
			Vector3 tempPos=(wayPoints[0] + wayPoints[wayPoints.Count-1])/2;//计算两个点的中点坐标，

			//GameObject go=(GameObject)Instantiate(line,tempPos,Quaternion.identity) ;//在两个点的中点处实例化线条，因为对物体的缩放，是从中心向两边延伸
			line.SetActive (true);
			line.transform.position = tempPos;
			//line.transform.rotation = Quaternion.identity;
			line.name="DrawLine";
			line.transform.right=(line.transform.position - wayPoints[0]).normalized;//改变线条的朝向
			//将屏幕坐标转化
			//------------------------------------------------------------------------------------
			Transform  start = line.transform;
			Transform  end = line.transform;
			start.position = Camera.main.ScreenToWorldPoint(wayPoints[0]);//转成世界坐标
			start.transform.InverseTransformPoint (start.position);       //转化成自身坐标
			Vector3 temp1 = start.position;
			//Debug.Log (temp1);                                            //该只需要临时保存，不保存，后面使用的时候值会变化
			end.position = Camera.main.ScreenToWorldPoint(wayPoints[wayPoints.Count-1]);//转成世界坐标
			end.transform.InverseTransformPoint (end.position);           //转化成自身坐标
			Vector3 temp2 = end.position;                                 //该只需要临时保存，不保存，后面使用的时候值会变化
			//Debug.Log (temp2);
			//使用已经转化好的坐标
			Vector3 tempPos2 = Vector3.zero;
			tempPos2=(temp1 + temp2)/2;//计算两个点的中点坐标，

			egg.transform.position = new Vector3(egg.transform.position.x, egg.transform.position.y, 0);
			line.transform.position = new Vector3(tempPos2.x, tempPos2.y, 0);
			//------------------------------------------------------------------------------------
			line.transform.eulerAngles  = new Vector3(0, 0, line.transform.eulerAngles.z);
			float distance=Vector3.Distance(wayPoints[0], wayPoints[wayPoints.Count-1]);//计算两点的距离
			Debug.Log (distance);
			if(distance < 30f)
			{
				line.GetComponent<CollisionDestination>().forceValue = 100f;
			}else if(distance < 80f){
				line.GetComponent<CollisionDestination>().forceValue = 300f;
			}else{
				line.GetComponent<CollisionDestination>().forceValue = 500f;
			}

			line.transform.localScale=new Vector3(distance * 0.045f,0.05f,1f);//延长线条，连接两点。
		}
	}
	void ClearLine()
	{
		line.SetActive (false);
		wayPoints.Clear ();
	}
	
}
